﻿using System.Collections.Generic;
using IQIGame.Onigao.Framework;
using LFloatMath.Collision2D;
using LFloatMath.Math;

namespace IQIGame.Onigao.Logic
{
    public partial class TargetSelect_Circle : TargetSelect
    {
        public override ETargetSelectType selectType => ETargetSelectType.Circle;

        public override bool selectByUnit => false;

        private LFloat raduis;
        private LFloat centerRange;
        protected override void OnInitialize(TargetSelectConfig rConfig)
        {
            base.OnInitialize(rConfig);
            if (rConfig.customConfig is TargetSelect_Circle_ConfigData rData)
            {
                this.raduis = new LFloat(true, rData.raduis);
                this.targetDisRange = new LFloat(true, rData.centerRange > 0 ? rData.centerRange : rData.raduis);
                this.centerRange = new LFloat(true, rData.centerRange);
            }
        }

        protected override void OnInitialize(IReadOnlyList<int> rTabConfig)
        {
            base.OnInitialize(rTabConfig);
            if (rTabConfig.Count > 1)
            {
                this.raduis = new LFloat(true, rTabConfig[0]);
                this.targetDisRange = new LFloat(true, rTabConfig[1] > 0 ? rTabConfig[1] : rTabConfig[0]);
            }
        }

        public override void TrySelect(SelectParam rParam, LVector2 rSelfPos, ref List<Unit> rTargets)
        {
            var rPos = rParam.pos;
            //验证自己与目标的距离，超过了要缩回来
            var rDis = rPos - rSelfPos;
            rDis = LVector2.ClampMagnitude(rDis, this.centerRange);
            rPos = rSelfPos + rDis;
            // 超出范围缩回来后会修改param内的数据
            rParam.pos = rPos;
            
            var rProxy = ColliderProxy.Fetch();
            rProxy.Init(CollisionUtil.GetCirclePrefab(raduis), rPos);
            rProxy.IsStatic = false;
            rProxy.LayerType = 0;

            this.CollisionCheck(rProxy, ref rTargets);
            ColliderProxy.Free(rProxy);
        }

        public override void OnReset()
        {
            base.OnReset();
            this.raduis = LFloat.zero;
            this.targetDisRange = LFloat.zero;
        }

        public override void Free()
        {
            ClassPool.Put(this);
        }
    }
}